package com.umfwechat.util;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.httpclient.ConnectTimeoutException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.umpay.http.platform2.HttpUtil;
import com.umpay.operation.common.ResMessage;
import com.umpay.operation.xml.XmlData;


/* ******************  类说明  *********************
 * class       :  RequestUtil
 * @author     :  lizhibin
 * @version    :  1.0  
 * description :  
 * @see        :                        
 * ************************************************/

public class RequestUtil {
	
	private static Logger logger = LoggerFactory.getLogger(RequestUtil.class);
	private XStream xstream = new XStream(new DomDriver());//序列化请求对象时使用
	
	/*
	 * ********************************************
	 * method name   : sendRequestForPost 
	 * description   : POST请求
	 * @return       : Object 响应
	 * @param        : @param urlstr
	 * @param        : @param request
	 * @param        : @return
	 * modified      : lizhibin ,  2013-12-3
	 * @see          : 
	 * *******************************************
	 */
	public Object sendRequestForPost(String urlstr, Object request) {
		return sendRequest("POST", urlstr, request);
	}
	
	
	/*
	 * ********************************************
	 * method name   : sendRequest 
	 * description   : 用于向基于Http协议的3.0平台发送同步请求
	 * @return       : Object
	 * @param        : @param method
	 * @param        : @param urlstr 请求地址,如果参数中带有中文，需要URLEncoder.encode(arg, "UTF-8")先进行转码
	 * @param        : @param request 请求报文
	 * @param        : @return 返回的是一个序列化好的对象
	 * modified      : lizhibin ,  2013-12-3
	 * @see          : 
	 * *******************************************
	 */
	private Object sendRequest(String method, String urlstr, Object request) {
		HttpURLConnection conn = null;
		InputStreamReader reader = null;
		Object obj = null;
		logger.info("***发送" + method + "请求：" + urlstr);
		try {
			URL url = new URL(urlstr);
			conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(12*1000);
			conn.setReadTimeout(60*1000);
			conn.setRequestMethod(method);
			if(request!=null)
			{
				logger.info("***请求数据：" + request.toString());
				conn.setDoOutput(true);
				conn.getOutputStream().write(xstream.toXML(request).getBytes("UTF-8"));
				conn.getOutputStream().flush();
				conn.getOutputStream().close();
			}

			int rCode = conn.getResponseCode();
			if (rCode == HttpURLConnection.HTTP_OK) {
				if (conn.getInputStream() != null) {
					reader = new InputStreamReader(conn.getInputStream(), "UTF-8");
					obj = xstream.fromXML(reader);
				}
				if(obj!=null){
					logger.info("***请求成功：" + obj.toString());
				}else{
					logger.info("***请求成功：" + obj);
				}
			} else {
				logger.info("***请求失败!***");
				obj= null;
			}
		} catch (Exception e) {
			logger.info("***请求失败!***", e);
			obj= null;
		} finally {
			try {
				reader.close();
				conn.disconnect();
			} catch (Exception e) {
			}
		}
		return obj;
	}
	/**
	 * desc:请求esoopay公共方法
	 * <p>创建人：linfangjian , Jun 21, 2016 8:40:02 PM</p>
	 * @param req
	 * @param serviceRest2
	 * @return
	 * @throws Exception
	 */
	public static ResMessage requestEsoopay2(com.umpay.operation.common.ReqMessage req, String url) throws Exception {
		ResMessage res = new ResMessage();
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			result = HttpUtil.httpPostForm2Xml(url, req.getReqMap());
		} catch (ConnectTimeoutException cte) {
			throw new ConnectFailureException("服务器未启动或连接超时或请求端口被禁用",cte);
		} catch (SocketTimeoutException se) {
			throw new ResponseTimeoutException("响应超时或网络环境差",se);
		} catch (ConnectException ce) {
			throw new ConnectFailureException("无效的ip或端口,请输入正确的ip或端口",ce);
		}  catch (IOException ie) {
			throw new ConnectFailureException("无效的url,请输入正确的url",ie);
		}
		res.setRpid((String) result.remove(XmlData.RPID));
		res.setRetCode((String) result.remove(XmlData.RETCODE));
		res.setRetMsg((String) result.remove(XmlData.RETMSG));
		res.put(result);
		return res;
	}
	
	public static ResMessage requestEsoopay2(com.umpay.sp.model.common.ReqMessage req, String url) throws Exception {
		ResMessage res = new ResMessage();
		Map<String, Object> reqMap = new HashMap<String, Object>();
		reqMap.putAll(req.getReqMap());
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			result = HttpUtil.httpPostForm2Xml(url, reqMap);
		} catch (ConnectTimeoutException cte) {
			throw new ConnectFailureException("服务器未启动或连接超时或请求端口被禁用",cte);
		} catch (SocketTimeoutException se) {
			throw new ResponseTimeoutException("响应超时或网络环境差",se);
		} catch (ConnectException ce) {
			throw new ConnectFailureException("无效的ip或端口,请输入正确的ip或端口",ce);
		}  catch (IOException ie) {
			throw new ConnectFailureException("无效的url,请输入正确的url",ie);
		}
		res.setRpid((String) result.remove(XmlData.RPID));
		res.setRetCode((String) result.remove(XmlData.RETCODE));
		res.setRetMsg((String) result.remove(XmlData.RETMSG));
		res.put(result);
		return res;
	}
}



